package com.tea.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tea.Model.Goods;
import com.tea.Model.GoodsSpec;
import com.tea.Model.dto.GoodsAddDTO;
import com.tea.Model.dto.GoodsOrderUpdateDTO;
import com.tea.Model.dto.GoodsPageDTO;
import com.tea.Model.dto.GoodsUpdateDTO;
import com.tea.Model.vo.GoodsDetailsVO;
import com.tea.Model.vo.GoodsPageVO;
import com.tea.Model.vo.GoodsSpecVO;
import com.tea.constans.GoodsConstant;
import com.tea.mapper.GoodsMapper;
import com.tea.mapper.GoodsSpecMapper;
import com.tea.utils.Result;
import com.tea.utils.StrToListUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class GoodsService extends ServiceImpl<GoodsMapper,Goods> {


    @Resource
    private GoodsMapper goodsMapper;
    @Resource
    private GoodsSpecService goodsSpecService;
    @Resource
    private GoodsSpecMapper goodsSpecMapper;

    /**
     * 根据分类 ID 查询商品列表
     *
     * @param categoryId 分类 ID
     * @return 商品列表
     */
    public List<Goods> listByCategoryId(String categoryId) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (categoryId != null && !categoryId.isEmpty()) {
            queryWrapper.eq("category_id", categoryId); // 添加分类 ID 查询条件
        }
        //添加排序条件：按display_order升序排列，display_order相同时按id升序
        queryWrapper.orderByAsc("display_order", "id");
        return list(queryWrapper);
    }

    /**
     * 根据商品id更新status
     * @param id 商品id
     * @param status 要更新的status值
     * @return 更新是否成功
     */
    public Result<Object> updateStatusById(Long id, String status) {
        if (!status.equals("0") && !status.equals("1")) {
            return Result.error("无效的状态码");
        }
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        Goods goods = new Goods();
        goods.setStatus(status);
        boolean update = update(goods, queryWrapper);
        if (update) {
            return Result.success("操作成功");
        }else {
            return Result.error("操作失败");
        }
    }

    @Transactional
    public Result<Object> deleteByIds(List<Integer> ids) {

        if (ids.isEmpty()) {
            return Result.error("商品编号不可为空");
        }
        
        // 逻辑删除商品
        boolean delResult = removeByIds(ids);
        
        if (delResult) {
            // 逻辑删除关联的商品规格
            UpdateWrapper<GoodsSpec> specUpdateWrapper = new UpdateWrapper<>();
            specUpdateWrapper.in("goods_id", ids)
                           .set("deleted", 1);
            goodsSpecService.update(specUpdateWrapper);
            
            return Result.success();
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 添加商品
     */
    @Transactional
    public Result<Object> add(GoodsAddDTO goodsAddDTO)  {

        //商品名称唯一性校验
      /*  if (StrUtil.isNotBlank(goodsAddDTO.getName())){
            QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
            goodsQueryWrapper.eq("name", goodsAddDTO.getName());
            Goods goods = goodsMapper.selectOne(goodsQueryWrapper);
            if (goods!=null){
                return Result.error("该商品名称已存在");
            }
        }*/

        //副图解析
        Goods goods = BeanUtil.copyProperties(goodsAddDTO, Goods.class);
        goods.setStatus(GoodsConstant.UNPUBLISHED);
        goods.setDeleted(0); // 设置为未删除状态
        List<String> otherImages = goodsAddDTO.getOtherImages();
        if (otherImages != null && !otherImages.isEmpty()) {
            goods.setOtherImages(otherImages.toString());
        }
        //商品基础信息入库
        boolean saveRes = save(goods);
        //规格信息入库
        if (saveRes){
            Long goodsId = goods.getId();
            goodsAddDTO.getSpecList().forEach(spec -> {
                spec.setGoodsId(goodsId);
                spec.setDeleted(0); // 设置规格为未删除状态
            });
            goodsSpecService.saveBatch(goodsAddDTO.getSpecList());
        }

        return Result.success("添加成功");
    }

    /**
     * 分页查询商品列表
     * @param pageNumber 页码
     * @param pageSize 每页大小
     * @param goodsPageDTO 查询条件
     * @return 分页结果
     */
    public PageInfo<GoodsPageVO> queryListWithPage(Integer pageNumber, Integer pageSize, GoodsPageDTO goodsPageDTO) {
        // 1.构建查询条件
        QueryWrapper<Goods> queryWrapper = buildQueryWrapper(goodsPageDTO);
        
        // 2.先查询总数（不分页）
        long total = goodsMapper.selectCount(queryWrapper);
        
        // 3.如果没有数据，直接返回空的分页结果
        if (total == 0) {
            PageInfo<GoodsPageVO> emptyPageInfo = new PageInfo<>();
            emptyPageInfo.setPageNum(pageNumber);
            emptyPageInfo.setPageSize(pageSize);
            emptyPageInfo.setTotal(0);
            emptyPageInfo.setList(new ArrayList<>());
            return emptyPageInfo;
        }
        
        // 4.开启分页查询
        PageHelper.startPage(pageNumber, pageSize);
        List<GoodsPageVO> list = queryList(goodsPageDTO);
        
        // 5.构建分页信息，手动设置正确的总数
        PageInfo<GoodsPageVO> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(total);
        
        return pageInfo;
    }
    
    /**
     * 构建查询条件
     */
    private QueryWrapper<Goods> buildQueryWrapper(GoodsPageDTO goodsPageDTO) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (goodsPageDTO.getName() != null && !goodsPageDTO.getName().isEmpty()) {
            queryWrapper.like("name", goodsPageDTO.getName());
        }
        if (goodsPageDTO.getCategoryId() != null && !goodsPageDTO.getCategoryId().isEmpty()) {
            queryWrapper.eq("category_id", goodsPageDTO.getCategoryId());
        }
        if (goodsPageDTO.getStatus() != null && !goodsPageDTO.getStatus().isEmpty()) {
            queryWrapper.eq("status", goodsPageDTO.getStatus());
        }
        //添加排序条件：按display_order升序排列，display_order相同时按id升序
        queryWrapper.orderByAsc("display_order", "id");
        return queryWrapper;
    }

    public List<GoodsPageVO> queryList(GoodsPageDTO goodsPageDTO) {
        //1.构建查询条件
        QueryWrapper<Goods> queryWrapper = buildQueryWrapper(goodsPageDTO);

        //2. 调用 Mapper 接口的 selectList 方法进行查询结果
        List<Goods> goods = goodsMapper.selectList(queryWrapper);

        // 提取商品 ID 列表
        List<Long> goodsIds = goods.stream()
                .map(Goods::getId)
                .collect(Collectors.toList());

        // 批量查询商品的最低价格
        List<Map<String, Object>> minPriceMaps = new ArrayList<>();
        if (!goodsIds.isEmpty()) {
            minPriceMaps = goodsSpecMapper.selectMinPricesByGoodsIds(goodsIds);
        }

        // 构建商品ID到最低价格的映射
        Map<Long, BigDecimal> minPriceMap = minPriceMaps.stream()
                .collect(Collectors.toMap(
                        map -> (Long) map.get("goods_id"),
                        map -> (BigDecimal) map.get("min_price"),
                        (existing, replacement) -> existing // 处理重复键的情况
                ));
                
        // 批量查询所有商品的规格信息
        final Map<Long, List<GoodsSpecVO>> goodsSpecMap = new HashMap<>();
        if (!goodsIds.isEmpty()) {
            QueryWrapper<GoodsSpec> specQueryWrapper = new QueryWrapper<>();
            specQueryWrapper.in("goods_id", goodsIds);
            List<GoodsSpec> allSpecs = goodsSpecService.list(specQueryWrapper);
            
            // 转换为VO并设置库存状态，按商品ID分组
            goodsSpecMap.putAll(allSpecs.stream()
                    .map(spec -> {
                        GoodsSpecVO specVO = BeanUtil.copyProperties(spec, GoodsSpecVO.class);
                        specVO.setStockStatus();
                        return specVO;
                    })
                    .collect(Collectors.groupingBy(GoodsSpecVO::getGoodsId)));
        }

        //3.解析副图集合、设置商品起步价格和规格信息
        return goods.stream()
                .map(good -> {
                    GoodsPageVO vo = BeanUtil.copyProperties(good, GoodsPageVO.class);

                    // 解析副图集合
                    List<String> images = StrToListUtil.parseStringToList(good.getOtherImages());
                    vo.setOtherImages(images);

                    // 设置起步价格（添加空值检查）
                    BigDecimal minPrice = minPriceMap.getOrDefault(good.getId(), BigDecimal.ZERO);
                    vo.setMinPrice(minPrice);
                    
                    // 设置商品规格信息
                    List<GoodsSpecVO> goodsSpecs = goodsSpecMap.getOrDefault(good.getId(), new ArrayList<>());
                    vo.setSpecs(goodsSpecs);

                    return vo;
                })
                .collect(Collectors.toList());
    }

    public GoodsDetailsVO getDetails(Integer id) {
        //查基础信息
        Goods goodsById = getById(id);
        if (goodsById == null) {
            return null;
        }
        //映射到vo类
        QueryWrapper<GoodsSpec> goodsSpecQueryWrapper = new QueryWrapper<>();
        goodsSpecQueryWrapper.eq("goods_id", id);
        List<GoodsSpec> goodsSpecs = goodsSpecService.list(goodsSpecQueryWrapper);
        
        // 转换为VO并设置库存状态
        List<GoodsSpecVO> goodsSpecVOs = goodsSpecs.stream()
                .map(spec -> {
                    GoodsSpecVO specVO = BeanUtil.copyProperties(spec, GoodsSpecVO.class);
                    specVO.setStockStatus();
                    return specVO;
                })
                .collect(Collectors.toList());
        
        GoodsDetailsVO goodsDetailsVO = BeanUtil.copyProperties(goodsById, GoodsDetailsVO.class);
        //处理副图集合
        if (goodsById.getOtherImages() != null) {
            List<String> imageUrls = StrToListUtil.parseStringToList(goodsById.getOtherImages());
            goodsDetailsVO.setOtherImages(imageUrls);
        }
        goodsDetailsVO.setSpecList(goodsSpecVOs);

        return goodsDetailsVO;
    }

    /**
     * 商品信息更新
     * */
    @Transactional
    public Result<Object> updateById(GoodsUpdateDTO goodsUpdateDTO) {
        //更新商品表信息
        List<String> otherImages = goodsUpdateDTO.getOtherImages();
        String otherImagesStr = "";
        if (otherImages != null && !otherImages.isEmpty()) {
            otherImagesStr = otherImages.toString();
        }
        Goods goods = BeanUtil.copyProperties(goodsUpdateDTO, Goods.class);
        goods.setOtherImages(otherImagesStr);
        updateById(goods);
        
        //更新规格表信息
        //1. 先物理删除原有规格（避免逻辑删除导致的主键冲突）
        goodsSpecMapper.deleteByGoodsIdPhysically(goods.getId());
        
        //2. 插入新的规格数据
        if (goodsUpdateDTO.getSpecList() != null && !goodsUpdateDTO.getSpecList().isEmpty()) {
            // 为新规格设置必要字段
            goodsUpdateDTO.getSpecList().forEach(goodsSpec -> {
                goodsSpec.setGoodsId(goods.getId()); // 设置商品ID
                goodsSpec.setDeleted(0); // 设置逻辑删除字段为0
                goodsSpec.setCreateTime(LocalDateTime.now()); // 设置创建时间为当前时间
            });
            goodsSpecService.saveBatch(goodsUpdateDTO.getSpecList());
        }

        return Result.success();
    }

    /**
     * 更新商品状态（上架/下架）
     * @param id 商品ID
     * @param status 状态：1-上架，0-下架
     * @return 操作结果
     */
    @Transactional
    public Result<Object> updateGoodsStatus(Long id, Integer status) {
        try {
            if (status == null || (status != 0 && status != 1)) {
                return Result.error("状态参数错误，只能为0（下架）或1（上架）");
            }

            // 更新商品状态
            UpdateWrapper<Goods> goodsUpdateWrapper = new UpdateWrapper<>();
            goodsUpdateWrapper.eq("id", id).set("status", status);
            this.update(goodsUpdateWrapper);

            // 更新商品规格状态
            UpdateWrapper<GoodsSpec> specUpdateWrapper = new UpdateWrapper<>();
            specUpdateWrapper.eq("goods_id", id).set("deleted", status == 1 ? 0:1);
            goodsSpecService.update(specUpdateWrapper);

            String message = status == 1 ? "商品上架成功" : "商品下架成功";
            return Result.success(message);
        } catch (Exception e) {
            String operation = status == 1 ? "上架" : "下架";
            return Result.error("商品" + operation + "失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新商品显示顺序
     * @param goodsOrderUpdateDTO 商品排序更新DTO
     * @return 更新结果
     */
    @Transactional
    public Result<Object> updateGoodsOrder(GoodsOrderUpdateDTO goodsOrderUpdateDTO) {
        try {
            List<GoodsOrderUpdateDTO.GoodsOrderItem> items = goodsOrderUpdateDTO.getItems();
            if (items == null || items.isEmpty()) {
                return Result.error("更新数据不能为空");
            }

            for (GoodsOrderUpdateDTO.GoodsOrderItem item : items) {
                if (item.getId() == null || item.getDisplayOrder() == null) {
                    return Result.error("商品ID和排序字段不能为空");
                }
                
                Goods goods = new Goods();
                goods.setId(item.getId());
                goods.setDisplayOrder(item.getDisplayOrder());
                
                QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id", item.getId());
                updateById(goods);
            }
            
            return Result.success("商品排序更新成功");
        } catch (Exception e) {
            return Result.error("更新商品排序失败：" + e.getMessage());
        }
    }
}
